const parseHTML = require("./parse-html");
const walk = require("./walk");

function generate(content) {
  const ast = parseHTML(content);
  let code = "";
  const varMap = new Map();

  walk(ast, {
    enter: (node) => {

      const key = node.name || node.type;
      if (varMap.has(key)) {
        varMap.set(key, varMap.get(key) + 1);
      } else {
        varMap.set(key, 1);
      }
      if (node.type === "Element") {
        code += `var ${node.name}${varMap.get(
          node.name
        )} = document.createElement('${node.name}');\n`;
      } else if (node.type === "Text") {
        code += `var t${varMap.get(
          node.type
        )} = document.createTextNode('${node.data}');\n`;
      } else if (node.type === "MustacheTag") {
        code += `document.createTextNode('MustacheTag');\n`;
      }
    },
    exit: (node) => {
      if (node.type === "Element") {
        code += `append(${node.name}${varMap.get(node.name)}, ${node.parent.type === "Fragment"
          ? "fragment"
          : node.parent.name + varMap.get(node.parent.name)
          });\n`;
      } else if (node.type === "Text") {
        code += `append(t${varMap.get(node.type)}, ${node.parent.type === "Fragment"
          ? "fragment"
          : node.parent.name + varMap.get(node.parent.name)
          });\n`;
      }
    },
  });

  return code;
}

module.exports = generate;
